<!--
 * @Version: 1.0
 * @Autor:
 * @Date: 2021-03-10 16:57:07
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-07-19 18:52:50
 * @Description:
-->
<template>
  <el-card class="app-container content_box" shadow="always">
    <div>
      <!-- title -->
      <!-- <div class="header_title_box">
        <h2>邮编分区管理</h2>
      </div> -->
      <!-- <div class="select_form_box">
        <div class="filter-container">
          <el-input v-model="queryParam.name" size="small" placeholder="搜索邮编分区" class="input-with-select mr16" @keyup.enter.native="handleSearch" />
        </div>
      </div> -->
      <form-selections :is-active="isActive" :items="formItems" :query-param.sync="queryParam" display="block" @handleSearch="handleSearch" />
      <div class="select_flex">
        <div class="operation_button_box">
          <el-button v-action="'zipCode@save'" icon="el-icon-circle-plus" size="small" type="success" @click="handleCreate()">新增邮编分区</el-button>
          <el-button v-action="'zipCode@zipImport'" type="primary" size="small" @click="importFile">导入</el-button>
        </div>
        <div>
          <el-button size="small" type="primary" class="filter-item search" icon="el-icon-search" @click="handleSearch">
            搜索
          </el-button>
          <el-button size="small" icon="el-icon-refresh" @click="handleRefresh">重置</el-button>
        </div>
      </div>
      <div v-loading="loading">
        <el-table ref="multipleTable" :data="data" tooltip-effect="dark" style="width: 100%" :max-height="screenHeigh" border fit @selection-change="handleSelectMulti">
          <el-table-column align="center" type="selection" width="55" />
          <el-table-column label="操作" align="center" fixed width="200px">
            <template slot-scope="scope">
              <span v-action="'zipCode@update'" class="edit_style" @click="handleUpdateNew(scope.row)">编辑</span>
              <span v-action="'zipCode@delete'" class="delete_style" @click="handleDelete(scope.row.id)">删除</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Origin" prop="origin" />
          <el-table-column align="center" label="Dest Zip" prop="dest_zip" />
          <el-table-column align="center" label="State" prop="state" />
          <el-table-column align="center" label="Zone" prop="zone" />
          <el-table-column align="center" prop="creator_name" label="创建人" />
          <el-table-column align="center" prop="created_at" label="创建时间" width="165" />
          <el-table-column align="center" prop="update_name" label="修改人">
            <template slot-scope="scope">
              {{ scope.row.update_name?scope.row.update_name:'-' }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="updated_at" label="更新时间" width="165" />
        </el-table>
        <el-pagination v-if="paginate.total > 0" class="pagination_box" background :current-page="paginate.current" :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="paginate.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
      <!-------- 回到顶部 ------------>
      <!-- <el-backtop :visibility-height="200" :bottom="100" target=".app-main .content_box" /> -->
      <el-backtop :visibility-height="60">
        <i class="el-icon-caret-top" />
      </el-backtop>
      <el-dialog :center="true" :title="title" :visible.sync="formVisible" width="750px" @close="handleCancel">
        <el-form :ref="formName" :model="formFieldsData" :rules="rules">
          <div class="header_title_box">
            <h2>邮编分区信息</h2>
          </div>
          <el-form-item label="Origin" :label-width="formLabelWidth" prop="origin">
            <!-- <el-input v-model.trim="formFieldsData.origin" size="small" placeholder="请输入Origin（仓库邮编）" autocomplete="off" clearable /> -->
            <el-select v-model="formFieldsData.origin" placeholder="请选择Origin（仓库邮编）" class="wfull" clearable filterable>
              <el-option v-for="item in virtualWarehouseList" :key="item.id" :label="`${item.name}(${item.zipcode})`" :value="item.zipcode">
                <span style="float: left">{{ item.name }} <b>({{ item.zipcode }})</b></span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="Dest Zip" :label-width="formLabelWidth" prop="dest_zip">
            <el-input v-model.trim="formFieldsData.dest_zip" size="small" placeholder="请输入Dest Zip（订单邮编）" autocomplete="off" clearable />
          </el-form-item>
          <el-form-item label="State" :label-width="formLabelWidth">
            <el-select v-model="formFieldsData.state" size="small" placeholder="请选择State" class="wfull" clearable>
              <el-option v-for="(item, index) in stateList" :key="index" :value="item.dict_data_name" :label="item.dict_data_name" />
            </el-select>
          </el-form-item>
          <el-form-item label="Zone" :label-width="formLabelWidth" prop="zone">
            <el-select v-model="formFieldsData.zone" size="small" placeholder="请选择Zone" class="wfull" clearable>
              <el-option v-for="(item, index) in zoneList" :key="index" :value="item.dict_data_name" :label="item.dict_data_name" />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer-center">
          <el-button @click="handleCancel">取 消</el-button>
          <el-button type="primary" @click="handleSubmitNew">确 定</el-button>
        </div>
      </el-dialog>
      <ImportDialog url="/zipImport" title="导入邮编分区" :form-visible.sync="formVisibleFile" @download="downLoad" @handleRefresh="handleRefresh" />
    </div>
  </el-card>

</template>

<script>
import formOperate from '@/layout/mixin/formOperate'
import {
  action
} from '@/directive/permission/index.js' // 权限判断指令
import ImportDialog from '@/components/importDialog/index.vue'
import { getEntityWarehouseList } from '@/utils/publicData'
import { downloadStream } from '@/utils/index'
import cacheList from '@/layout/mixin/cacheList'
export default {
  name: 'BasicsZipCode',
  directives: {
    action
  },
  components: { ImportDialog },
  mixins: [formOperate, cacheList],
  data() {
    return {
      otherHeight: 365,
      componentName: 'BasicsZipCode',
      virtualWarehouseList: [],
      formVisibleFile: false,
      url: '/zipCode',
      queryParam: {
        name: ''
      },
      formItems: [
        {
          label: '邮编分区',
          key: 'name',
          type: 'input',
          placeholder: '请输入邮编分区'
        }
      ],
      option: [{
        value: 2,
        label: '禁用'
      },
      {
        value: 1,
        label: '启用'
      }
      ],
      loading: false,
      formVisible: false,
      formFieldsData: {
        dest_zip: '',
        origin: '',
        state: '',
        zone: ''
      },
      formName: 'zipCodes',
      formLabelWidth: '150px',
      rules: {
        dest_zip: [
          { required: true, message: '请输入dest_zip', trigger: 'blur' },
          { pattern: /^([0-9\-]+)$/, message: '请输入数字或者- ', trigger: 'blur' }
        ],
        origin: [
          { required: true, message: '请输入origin', trigger: 'blur' },
          { pattern: /^([0-9\-]+)$/, message: '请输入数字或者- ', trigger: 'blur' }
        ],
        state: [{ required: true, message: '请输入邮政区号', trigger: 'blur' }],
        zone: [{ required: true, message: '请选择Zone', trigger: 'blur' }]
      },
      stateList: [],
      zoneList: []
    }
  },
  created() {
    const vm = this
    vm.getDic() // 获取字典
    getEntityWarehouseList().then(data => {
      vm.virtualWarehouseList = data
    })
  },
  methods: {
    // 下载
    downLoad() {
      const vm = this
      vm.$http
        .get('/zipImport/template', { responseType: 'blob' })
        .then((res) => {
          downloadStream(res, '邮编分区模板.xlsx')
        })
    },
    getDic() {
      const vm = this
      vm.$cache.getDic('zipcode_state').then(res => {
        vm.stateList = res
      })
      vm.$cache.getDic('zipcode_zone').then(res => {
        vm.zoneList = res
      })
    },
    // 导入
    importFile() {
      this.formVisibleFile = true
      console.log('=========暂未实现=====')
    },
    beforeCreate() {
      Object.keys(this.formFieldsData).forEach(k => {
        this.formFieldsData[k] = ''
      })
    },
    handleUpdateNew(data) {
      this.id = data.id
      this.$http.get(`zipCode/${data.id}`).then(res => {
        const dataObj = res.data
        this.formFieldsData = dataObj
        this.formVisible = true
      })
    },
    handleSubmitNew() {
      this.$refs['zipCodes'].validate((valid) => {
        if (valid) {
          // 编辑
          if (this.id) {
            this.$http.put(`zipCode/${this.formFieldsData.id}`, this.getData()).then(response => {
              if (response.code === 10000) {
                this.$message.success('编辑成功')
                this.formVisible = false
                this.resetFormFields()
                this.handleRefresh()
                this.id = null
              } else {
                this.$message.error(response.message)
              }
            })
          } else {
            // 判断个人信息
            this.$http.post('zipCode', this.formFieldsData).then(response => {
              if (response.code === 10000) {
                this.$message.success('添加成功')
                this.formVisible = false
                this.resetFormFields()
                this.handleRefresh()
              } else {
                this.$message.error(response.message)
              }
            })
          }
        }
      })
    },
    // 获取添加参数组合
    getData() {
      const data = {
        origin: this.formFieldsData.origin,
        dest_zip: this.formFieldsData.dest_zip,
        state: this.formFieldsData.state,
        zone: this.formFieldsData.zone
      }
      return data
    }
  }
}

</script>

<style lang="scss" scoped>
.width500 {
  width: 500px !important;
}
</style>
